using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.MaterialManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;
using RBAC.Read.Api.Application.Dto.ERP;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 物料分类树形列表 处理器
    /// </summary>
    public class GetMaterTypeTreeHandler : IRequestHandler<GetMaterTypeTreeCommand, APIResult<List<MaterTypeTreeDto>>>
    {
        private readonly IBaseRepository<MaterType> materTypeRepository;
        private readonly ILogger<GetMaterTypeTreeHandler> logger;

        public GetMaterTypeTreeHandler(
            IBaseRepository<MaterType> materTypeRepository,
            ILogger<GetMaterTypeTreeHandler> logger)
        {
            this.materTypeRepository = materTypeRepository;
            this.logger = logger;
        }

        public Task<APIResult<List<MaterTypeTreeDto>>> Handle(GetMaterTypeTreeCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<MaterTypeTreeDto>>();
            try
            {
                logger.LogInformation("开始获取物料分类树形列表");
                var allTypes = materTypeRepository.GetAll();

                // 构建字典
                var dtoMap = allTypes.ToDictionary(
                    t => t.Id,
                    t => new MaterTypeTreeDto { Id = t.Id, TypeCode = t.TypeCode, TypeName = t.TypeName, Children = new List<MaterTypeTreeDto>() }
                );

                // 组装树
                List<MaterTypeTreeDto> roots = new List<MaterTypeTreeDto>();
                foreach (var t in allTypes)
                {
                    bool isRoot = !t.ParentId.HasValue || t.ParentId.Value == 0;
                    if (isRoot)
                    {
                        roots.Add(dtoMap[t.Id]);
                    }
                    else if (dtoMap.TryGetValue(t.ParentId!.Value, out var parentDto))
                    {
                        parentDto.Children.Add(dtoMap[t.Id]);
                    }
                    else
                    {
                        // 找不到父节点，按根处理，避免数据断裂
                        roots.Add(dtoMap[t.Id]);
                    }
                }

                result.Code = APIEnums.Success;
                result.Data = roots;
                result.Msg = "获取物料分类树成功";
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取物料分类树失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取物料分类树失败";
                result.Data = new List<MaterTypeTreeDto>();
            }

            return Task.FromResult(result);
        }
    }
}
